<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="优惠券名称" prop="couponId">
      <el-select clearable v-model="queryParams.couponId" filterable allow-create placeholder="请选择优惠卷名称">
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.couponName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="是否已兑换" prop="ifConversion">
        <el-select v-model="queryParams.ifConversion" placeholder="请选择是否已兑换" clearable size="small">
          <el-option
            v-for="dict in ifConversionOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="领取时间" prop="getTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.getTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择领取时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button  size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon=""-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['shopping:mallCdk:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['shopping:mallCdk:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shopping:mallCdk:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['shopping:mallCdk:export']"
          v-if="true"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :height="tableHeight" :data="mallCdkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" show-overflow-tooltip />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="优惠券名称" align="center" prop="couponName" />
      <el-table-column label="兑换码" align="center" prop="cdked" />
<!--      <el-table-column label="领取人id" align="center" prop="memberId" />-->
      <el-table-column label="是否已兑换" align="center" prop="ifConversion">
        <template slot-scope="scope">
          <dict-tag :options="ifConversionOptions" :value="scope.row.ifConversion"/>
        </template>
      </el-table-column>
      <el-table-column label="领取时间" align="center" prop="getTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.getTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shopping:mallCdk:remove']"
            v-if="scope.row.ifConversion == 'N'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改批量生成CDK对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否已兑换" prop="ifConversion">
          <el-select v-model="form.ifConversion" placeholder="请选择是否已兑换">
            <el-option
              v-for="dict in ifConversionOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领取时间" prop="getTime">
          <el-date-picker clearable size="small"
                          v-model="form.getTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择领取时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMallCoupons,listMallCdk, getMallCdk, logicDelMallCdk, addMallCdk, updateMallCdk, exportMallCdk } from "@/api/shopping/mallCdk";
export default {
  name: "MallCdk",
  data() {
    return {
      //获取到优惠券名称
      getCouponName:"",
      //优惠券下拉查询
      options:[],
      tableHeight:0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 批量生成CDK表格数据
      mallCdkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否已兑换字典
      ifConversionOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cdked:null,
        couponId: null,
        memberId: null,
        ifConversion: null,
        getTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };

  },

  created() {
    this.getList();
    this.selectMallCoupons();
    this.calHeight()
    this.getDicts("sys_yes_no").then(response => {
    this.ifConversionOptions = response.data;
    });
  },
  watch: {
    'showSearch':'calHeight'
  },
  mounted() {
    document.addEventListener('visibilitychange', this.handleVisiable)
  },
  destroyed() {
    document.removeEventListener('visibilitychange', this.handleVisiable)
  },

  methods: {
    handleVisiable(e) {
      if (e.target.visibilityState === 'visible') {
        // 要执行的方法
        // this.function();
      }
    },

      function() {
       let  url = location.href="http://localhost/shopping/mallCdk"; //把当前页面的地址赋给变量 url
      //  //  //分切变量 url 分隔符号为 "#"
      //  //  if( url.indexOf("#") == -1){ //如果url后没有#
      //  //    url += "#"; //加入 #
      //  //    self.location.replace(url); //刷新页面
      //  //  }
        window.location.reload(url) // 第一种方式
      },
    //优惠券查询
    selectMallCoupons(){
      listMallCoupons().then(response => {
        this.options = response.rows;
      });

    },
    calHeight () {
          this.$nextTick(() => {
              const rect = this.$refs.appcontainer.getBoundingClientRect();
              let height= this.$refs.queryForm.$el.offsetHeight;
              this.tableHeight = rect.height-height-120;
          })
      },
    /** 查询批量生成CDK列表 */
    getList() {
      this.loading = true;
      listMallCdk(this.queryParams).then(response => {
        this.mallCdkList = response.rows;
        this.getCouponName = this.mallCdkList.map(item => item.couponName);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        couponId: null,
        memberId: null,
        ifConversion: null,
        getTime: null,
        delState: null,
        delUser: null,
        cdked:null,
        delType: null,
        delTime: null,
        createBy: null,
        createType: null,
        createTime: null,
        updateBy: null,
        updateType: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch=false;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加批量生成CDK";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMallCdk(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改批量生成CDK";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMallCdk(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMallCdk(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return logicDelMallCdk(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.queryParams.couponId == null){
        this.msgError("请先根据优惠券查询以后再导出");
      }
      if (this.queryParams.couponId!=null){
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出"+ this.getCouponName[0] +"的兑换码吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMallCdk(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
    }
  }
};
</script>
